import {
    observable,
    action,
    autorun,
    toJS
} from 'mobx';
import {
    message,
    Modal
} from 'antd';
import {
    WeaForm
} from 'comsMobx';
import _ from "lodash";
import {
    ListStore
} from './listStore';
import {
    isHasKey
} from '../util/index';
import GetFormJson from '../util/getFormJson';
import {
    WeaLocaleProvider
} from 'ecCom';

import * as Apis from '../apis/govern';
import objectAssign from 'object-assign';
const getLabel = WeaLocaleProvider.getLabel;

export default class TopStore extends ListStore {
    wftypes = []; //存储所有card信息
    createwflabels = {};
    tabDatas = [];

    @observable condition = [];

    @observable showDatas = {
        typesShow: [], //is数据为空
        typesCols: [], //card数据源
        commonuse: ''
    }

    @observable dialogDatas = {
        componentDatas: [],
        taskComponentDatas: [],
        optionsDatas: {}
    }

    @observable value = "";
    @observable tabkey = '1';
    @observable abcSelected = "";
    @observable loading = false;

    importData = [];
    importValue = "";
    @observable importDataShow = [];
    @observable listStore = {};
    @observable listStoreB = {};
    @observable listStoreB1 = {}; //克隆的数据，添加按钮时，所复制数据源
    @observable formB = new WeaForm();
    @observable sourceDataMobx = [];
    @observable visibleTip = false;
    categoryid = ""; //明确是哪个类别新建的
    suffix = 1; //为了给domkey加后缀
    existFormB = false; //子任务明细是否存在
    existForm = false; //子项目明细是否存在
    uploadProjectRefs; // 存储事项的refs
    uploadTaskRefs; // 存储任务的refs
    @observable uploadSize = []; //上傳個數
    @observable submitFlag = false; //上传标识，提交的时候true
    @observable changeFlag = false;

    uploadid; //关闭弹出的窗口的id
    @observable uploadRefSize = 0; //上傳組件個數

    @observable wfOperateInfo = {
        curOperWfid: 0,
        showBeagenters: false,
        showImportWf: false
    };
    @observable loaded = false;
    @observable isRight = false;
    @observable cubeLayoutParame = {};//装载布局请求入参
    beforeIdList = []; //记录上次打开的弹框id，数组只有两个元素
    cancelIdList = []; //记录上次打开的弹框id，数组只有两个元素
    arrayValid = [];
    @observable dodel = false;
    @observable Card = {};
    @observable startdate = '';
    @observable enddate = '';
    @observable isopenModal = false;
    @observable formBCellLength = 0;
    @observable delIndex = 0;//删的是第几个子任务
    @observable astartdate = '';
    @observable aenddate = '';

    constructor(props) {
        super(props);
        this.changeTab = this.changeTab.bind(this);
        this.setSearchValue = this.setSearchValue.bind(this);
        this.openModal = this.openModal.bind(this);
        this.initForm = this.initForm.bind(this);
        this.saveProInfo = this.saveProInfo.bind(this);
        this.save = this.save.bind(this);
        this.clearForm = this.clearForm.bind(this);
        this.getActionSetting = this.getActionSetting.bind(this);
        this.getuploadProjectRef = this.getuploadProjectRef.bind(this);
        this.getuploadTaskRef = this.getuploadTaskRef.bind(this);
        this.validDateHandle = this.validDateHandle.bind(this);
    }
    //存储事项的refs
    @action
    getuploadProjectRef(dom) {
        this.uploadProjectRefs = dom;
    }

    @action
    getuploadTaskRef(dom) {
        this.uploadTaskRefs = dom;
        // for(let ref in this.uploadTaskRefs){
        //     console.log("refs",ref);
        // }
    }

    //执行事项的上传
    @action
    doProUpload = () => {
        for (let ref in this.uploadProjectRefs) {
            this.uploadProjectRefs[ref].doUpload();
            // console.log("project",ref);
        }
    }

    @action
    doTaskUpload = () => {
        for (let ref in this.uploadTaskRefs) {
            this.uploadTaskRefs[ref].doUpload();
            // console.log("task",ref);
        }
    }

    @action
    updateForm = (listT, listB, upload, form, field, uploadSize) => {
        if (listB && listB.length == 0 && listT && listT.length == 0 && !this.submitFlag) {
            upload[field.domkey] = "";
            form.updateFields(upload); //赋值绕过检验规则
            // console.log("form", form.getFormParams());
        }
        if (listT && listT.length > 0 && this.submitFlag) {
            let imagefileids = [];
            listT.map((item, index) => {
                imagefileids.push(item.fileid);
            })
            upload[field.domkey] = imagefileids.join(",");
            form.updateFields(upload);

            uploadSize = uploadSize.push("1"); //注意并发
            let uploadsize = this.uploadRefSize;
            if (uploadSize == uploadsize) {
                this.saverPro();
                this.closeModal();
            }
        }
        //無文件保存
        if (listB && listB.length == 0 && listT && listT.length == 0 && this.submitFlag) {
            uploadSize = uploadSize.push("1"); //注意并发
            let uploadsize = this.uploadRefSize;
            if (uploadSize == uploadsize) {
                this.saverPro();
                this.closeModal();
            }
        }
    }

    //初始化
    @action
    initDatas(params = {}) {
        this.loading = true;
        params.tabkey = this.tabkey;
        Apis.getCategoryGroup(params).then(result => {
            if (parseInt(result.status) == 1) {
                this.loading = false;
                if (result.data.length == 0) {
                    const {tabs = [] ,createwflabels,} = result;
                    this.createwflabels = createwflabels;
                    this.tabDatas = tabs;
                    this.loaded = true;
                    this.isRight = true;
                } else {
                    const {
                        data,
                        createwflabels,
                        tabs = []
                    } = result;
                    const {
                        hasStruct
                    } = params;
                    this.wftypes = data;
                    this.createwflabels = createwflabels;
                    this.tabDatas = tabs;
                    this.showDatas = {
                        ...this.showDatas
                    };
                    this.setUpdate();
                }
            } else {
                message.error(result.error);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    /**
     * 加载弹出表单字段
     */
    @action
    initForm() {
        // this.formB = new WeaForm();
        let _this = this;
        this.condition = [];
        this.listStoreB.condition = []
        this.cubeLayoutParame = {};
        const params = { "categoryid": _this.categoryid };
        _this.formBCellLength = 0;
        _this.delIndex = 0;
        this.dodel = false;
        Apis.governSetupInit({
            ...params
        }).then(result => {
            if(result.isopen === true){
              _this.cubeLayoutParame = {...result.data};
            }
            Object.keys(result).forEach(function(key){
                if(key.includes('condition')){
                    result[key][0].items.map((item)=>{
                        if(item.conditionType.includes('RICHTEXT')){
                            item.ckConfig = {...item.ckConfig,"startupFocus":false}
                        }
                    })
                }
           
           });
            const fields = result.condition2[0].items;
            _this.existForm = isHasKey(result, "condition1", "items");
            _this.existFormB = isHasKey(result, "condition2", "items");
            if(_this.existFormB){
                _this.formBCellLength = result.condition2[0].items.length;
            }
            if (parseInt(result.status) == 1) {
                _this.mackCondition(result);
                if(document.getElementsByTagName("input")[2]) document.getElementsByTagName("input")[2].focus();
            } else {
                message.error(result.error);
            }
        }).then(()=>{
            if(this.existFormB){
                this.listStoreB1.condition[0].items.map((item)=>{
                    if(item.conditionType.includes('RICHTEXT')){
                        item.ckConfig = {...item.ckConfig,"startupFocus":true}
                    }
                })
            }
        });
    }
    @action
    mackCondition(result) {
        let f = _.cloneDeep(result);
        let dbFormData = _.has(f, 'condition1') ? _.pick(f, ['condition1']) : [];
        let fromDataB = _.has(f, 'condition2') ? _.mapKeys(_.pick(result, ['condition2']), (value, key) => key.slice(0, -1)) : [];
        if (this.existForm) GetFormJson.setFormJson(dbFormData, this.form, "condition1", ["name", "remark"], [1, 2], [4, 9], [20, 15], this.getCondition, this, true); //事项阶段
        //任务阶段
        if (this.existFormB) {
            fromDataB = GetFormJson.setFormJson(fromDataB, this.formB, "condition", ["name", "remark"], [1, 2], [4, 9], [18, 15], this.getCondition, this, false);
            this.listStoreB = _.cloneDeep(fromDataB);
            this.listStoreB1 = fromDataB;
            // console.log("this.listStoreB1")
            this.formB && !this.formB.isFormInit && this.formB.initFormFields(fromDataB.condition);
        }

        //防止删除
    }
    @action
    getCondition(condition, _this) {
        _this.condition = condition;
    }

    @action
    getFormParamsProj() {
        return this.form.getFormParams();
    }
    @action
    getFormParamsTask() {
        return this.formB.getFormParams();
    }
    //将domkey存在数组,domkeyList:数组中存储所有的domkey；everyDomkeyList：数组中存储每个condition的domkey
    @action
    getdomkeyList() {
        let len = this.listStoreB["condition"].length; //19.01.07子任务最后一条删除后可正常保存
        let domkeyList = [];
        let everyDomkeyList = [];
        this.listStoreB["condition"].map((c) => {
            c.items.map((i) => {
                let domkeyitemList = [];
                i.domkey.map((d) => {
                    domkeyitemList.push(d);
                });
                domkeyList = domkeyList.concat(domkeyitemList);
            });
        });
        len > 0 && this.listStoreB["condition"][0].items.map((i) => {
            let domkeyitemList = [];
            i.domkey.map((d) => {
                domkeyitemList.push(d);
            });
            everyDomkeyList = everyDomkeyList.concat(domkeyitemList);
        });
        domkeyList = _.flattenDeep(domkeyList);
        everyDomkeyList = _.flattenDeep(everyDomkeyList);
        return {
            domkeyList,
            everyDomkeyList
        };
    }

    /**
     * 子任务明细添加方法
     * @param {*} index
     */
    @action
    btnAddClick(index, callBack) {
        this.visibleTip = false;
        this.suffix++
        let sourceData = {};
        if (this.existFormB) {
            sourceData = _.cloneDeep(toJS(this.listStoreB1["condition"][0]));
            //构建新的domkey,例name->name1,remark->remark1
            sourceData.items.map((i) => {
                let newDomkey = [];
                i.domkey.map((d) => {
                    d = `${d}标${this.suffix}`;
                    newDomkey.push(d);
                });
                i.domkey.length = 0;
                i.domkey = [...newDomkey];
            });
            this.listStoreB["condition"].splice((index + 1), 0, sourceData);
            sourceData.items.map((i, index) => {
                this.formB.initFormFieldObj([i]);
            });
            const len = this.listStoreB["condition"].length;
            if (len === 0) { //19.1.18删除会清除数据BUG
                this.formB = new WeaForm();
                this.formB.setCondition(this.listStoreB["condition"]); //19.01.15任务删光再添加不保存
            }
        } else {
            message.error(`${getLabel('83638,724,32867,18550', '请配置督办任务明细字段')}`)
        }
        if (callBack) {
            callBack();
        }
    }
    /**
    * 子任务明细删除方法
    * @param {*} index
    */
    @action
    btnDelClick(index) {
        this.delIndex = index;
        this.visibleTip = false;
        this.dodel = true;
        this.listStoreB["condition"].splice(index, 1);
        const formValues = this.formB.getFormDatas();
        this.formB = new WeaForm();
        this.formB.initFormFields(toJS(this.listStoreB.condition));
        this.formB.updateFields(formValues);
        const len = this.listStoreB["condition"].length;
        if (len === 0) {
            this.formB = new WeaForm();
            this.formB.setCondition(this.listStoreB["condition"]); //19.01.15任务删光再添加不保存
        }
        //最后一条不能删
        // let len = this.listStoreB["condition"].length
        // if (len > 1) {
        //     this.listStoreB["condition"].splice(index, 1);
        //     this.listStoreB["condition"].map((c, index) => {
        //         c.title = (index + 1).toString();
        //     });
        // } else {
        //     this.visibleTip = true;
        // }
    }

    /**
     * 新建保存方法
     * @param {*} params
     */
    @action
    saveProInfo(params) {
        Apis.saveProInfo(params).then(result => {
            if (result.status == "1") {
                message.success(`${getLabel('83551', '保存成功！')}`);
                hrefTaskInfo(result.id);
            } else if (result.status == -3) {
                message.warning(result.error, 5);
                // this.openModal(params.categoryid, false);
                // return ;
            } else {
                message.error(result.error)
            }
        }).catch(error => {
            message.warning(getLabel('501166', "输入内容过多了"));
            this.openModal(params.categoryid, true);
            return;
        });
    }
    /**
     * 取消未保存时清空表单
     * @param {*} params
     */
    @action
    clearForm() {
        this.form.resetForm();
        this.formB.resetForm();
        this.uploadTaskRefs = null;
        this.uploadProjectRefs = null;
        this.submitFlag = false;
        this.uploadRefSize = 0;
        this.dodel = false;
        this.arrayValid = [];
    }

    @action
    getCardStorefun = (store)=>{
        this.Card = store;
    }

    /**
     * 保存操作校验
     * @param {*} id 保存的是哪条新建
     */
    @action
    save(id) {
        if (Object.keys(this.cubeLayoutParame).length > 0) {//建模布局保存方法
            //   const { Card } = (window.weaCube && window.weaCube.store) || {};
            const { ecmeDoSubmit } = this.Card.Actions;
            ecmeDoSubmit().then((data) => {
                let resultJson = data.JSONStr;
                let governMainTable ={};
                for(let key in resultJson.mainTable){
                     governMainTable = Object.assign(governMainTable,resultJson.mainTable[key]) ;
                }
                let mainTableJsonStr = {'mainTable':governMainTable};
                let newJsonStr = Object.assign(resultJson,mainTableJsonStr)
                data.JSONStr = JSON.stringify(newJsonStr);
                this.saveProInfo({
                    categoryid: this.categoryid,
                    ...data
                });
                this.openModal(this.categoryid, false);
            })
            return true;
        }else{
            this.validDateHandle();
            if(this.isopenModal) return false;
            if(!this.isopenModal){
                let formValid = false;
                let formBValid = false;
                let len = this.listStoreB["condition"].length;
                let isExistTask = (len > 0) && this.existFormB; //19.01.15任务删光再添加不保存
                if (this.existForm) {
                    // console.log("form",this.form.getFormParams());
                    this.form.validateForm().then(f => {
                        if (f.isValid) {
                            formValid = true;
                            if (isExistTask ? formValid && formBValid : formValid) {
                                this.subBtn(id);
                                // this.openModal(id, false);
                            }
        
                        } else {
        
                            f.showErrors();
                            this.openModal(id, true)
                        }
                    });
                }
                if (isExistTask) {
                    // console.log("fromb",this.formB.getFormParams())
                    if (this.dodel === true) {//#587348 概述：E9，督办，立项，删除一个必填项为空的子任务后，点击保存，没反应
                        this.checkValidate().then(data => {
                            let validateFormResult = this.arrayValid.every((a) => {
                                return a === true;
                            })
                            //console.log("validateFormResult", validateFormResult)
                            if (validateFormResult === true) {
                                formBValid = true;
                                if (formValid && formBValid) {
                                    this.subBtn(id);
                                }
                            } else {
                                this.formB.validateForm().then(f => {
                                    if (!f.isValid) {
                                        f.showErrors();
                                    }
                                    this.openModal(id, true)
                                });
                                this.openModal(id, true)
                            }
                        })
                    } else {
                        this.formB.validateForm().then(f => {
                            if (f.isValid) {
                                formBValid = true;
                                if (formValid && formBValid) {
                                    this.subBtn(id);
                                }
                            } else {
                                if (!f.isValid) {
                                    f.showErrors();
                                }
                                this.openModal(id, true)
                            }
                        });
                    }
        
                }
                if (!(this.existForm) && !(this.existFormB)) {
                    this.subBtn(id);
                    // this.openModal(id, false);
                }
            }
        }
    }
    @action
    validDateHandleErr1=()=>{
        message.error(`${getLabel('511480', '开始日期时间不能大于结束日期时间')}`);
        this.validDateHandleCom();
    }
    // @action
    // validDateHandleErr2=()=>{
    //     message.error(`${getLabel('511481', '结束日期时间不能小于当前日期时间')}`);
    //     this.validDateHandleCom();
    // }
    @action
    validDateHandleCom=()=>{
        this.openModal(this.categoryid, true);
        this.isopenModal = true;
        return false;
    }
    @action
    validDateHandlePro=(startdatekey='',starttimekey='',enddatekey='',endtimekey='')=>{
        if (this.form.has(startdatekey) && this.form.has(enddatekey)) { 
            let startdate =  this.form.has(starttimekey) ? this.form.$(startdatekey).value.concat(" ",this.form.$(starttimekey).value).replace(/-/g, '/') : this.form.$(startdatekey).value.concat(" ", "00:00"),
                enddate = this.form.has(endtimekey) ? this.form.$(enddatekey).value.concat(" ",this.form.$(endtimekey).value).replace(/-/g, '/') : this.form.$(enddatekey).value.concat(" ", "00:00");
                if (startdate !== '' && enddate !== '' && new Date(startdate) > new Date(enddate)) {
                    this.validDateHandleErr1();
                }
                // if(new Date(enddate) < new Date(new Date())){
                //     this.validDateHandleErr2();
                // }
        }
    }
    @action
    validDateHandleTask1=(startdate='',enddate='')=>{
        if(startdate !== '' && enddate !== '' && new Date(startdate) > new Date(enddate)){
            this.validDateHandleErr1();
        }
        // if(new Date(enddate) < new Date() ) {
        //     this.validDateHandleErr2();
        // }
    }
    validDateHandleTaskStr=(key='',fieldkey)=> (fieldkey.replace(/\s*/g,"").replace(/\"/g, "").toString()).startsWith(key)

    /**
     * 开始日期不能大于结束日期
     */
    @action
    validDateHandle(){
        this.startdate = '';
        this.enddate = '';
        this.astartdate = '';
        this.aenddate = '';
        this.isopenModal = false;
        this.validDateHandlePro('startdate','starttime','enddate','endtime');
        this.validDateHandlePro('astartdate','astarttime','aenddate','aendtime');
       
        if (this.formB) {
            const _this = this;
            _this.formB.map((field,index) => {
                    if(this.validDateHandleTaskStr('startdate',field.key)){
                        _this.startdate =  field.values().concat(" ", "00:00")
                    }else if(this.validDateHandleTaskStr('enddate',field.key)){
                        _this.enddate = field.values().concat(" ", "00:00")
                    }else if(this.validDateHandleTaskStr('starttime',field.key)){
                        const starttime = field.values();
                        _this.startdate = _this.startdate.split(" ")[0].concat(" ",starttime).replace(/-/g, '/');
                    }else if(this.validDateHandleTaskStr('endtime',field.key)){
                        const endtime = field.values();
                        _this.enddate = _this.enddate.split(" ")[0].concat(" ",endtime).replace(/-/g, '/');
                    }else if(this.validDateHandleTaskStr('astartdate',field.key)){
                        _this.astartdate =  field.values().concat(" ", "00:00")
                    }else if(this.validDateHandleTaskStr('aenddate',field.key)){
                        _this.aenddate = field.values().concat(" ", "00:00")
                    }else if(this.validDateHandleTaskStr('astarttime',field.key)){
                        const starttime = field.values();
                        _this.astartdate = _this.astartdate.split(" ")[0].concat(" ",starttime).replace(/-/g, '/');
                    }else if(this.validDateHandleTaskStr('aendtime',field.key)){
                        const endtime = field.values();
                        _this.aenddate = _this.aenddate.split(" ")[0].concat(" ",endtime).replace(/-/g, '/');
                    }
                    if( index != 0 && index % (_this.formBCellLength-1) == 0 ){
                        // console.log("_this.delInde",this.delIndex,this.formBCellLength,index,this.dodel)
                    //    const goon = (_this.dodel === true) ? ((_this.delIndex+1) != index/(_this.formBCellLength-1) ? true : false) : true;
                    const goon = true;
                        if(goon){
                            _this.validDateHandleTask1(_this.startdate,_this.enddate);
                            _this.validDateHandleTask1(_this.astartdate,_this.aenddate);
                        }
                        _this.startdate = '';
                        _this.enddate = '';
                        _this.astartdate = '';
                        _this.aenddate = '';
                    }
            })
        }
    }
    /**
     * 弹出窗口保存方法点击事件
     */
    @action
    subBtn = (id) => {
        this.uploadid = id;
        this.submitFlag = true;
        let uploadProRefSize = Object.getOwnPropertyNames(this.uploadProjectRefs).length; //获取上传组件个数
        let uploadTaskRefSize = Object.getOwnPropertyNames(this.uploadTaskRefs).length;
        this.uploadRefSize = uploadProRefSize + uploadTaskRefSize;
        if (uploadProRefSize > 0) { //事项里有上传组件执行上传，在回调函数里保存事项
            this.doProUpload()
        }
        if (uploadTaskRefSize > 0) {
            this.doTaskUpload();
        }
        if (uploadProRefSize == 0 && uploadTaskRefSize == 0) { //没有上传组件的时候直接保存任务
            this.saverPro();
            this.openModal(id, false);
        }
    }

    @action
    closeModal = () => {
        this.openModal(this.uploadid, false);
    }



    saverPro = () => {
        let postDataTask = [];
        let chunkList = [];
        let postToh = {};
        let task = this.getFormParamsTask();
        let project = this.getFormParamsProj(); //{"",""}
        if (this.existFormB) { //存在子任务明细
            let len = this.getdomkeyList().everyDomkeyList; //获取单个condition里面的Domkey的key存于数组中
            let byList = this.getdomkeyList().domkeyList; //获取所有condition里面的Domkey的key存于数组中
            let size = len.length;
            chunkList = _.chunk(byList, size);
            chunkList.map((c) => {
                postDataTask.push(_.pick(JSON.parse(JSON.stringify(task)), c));
            });
            //去掉Domkey的key的下标
            postDataTask = postDataTask.map((p, index) => {
                p = Object.assign({}, p, {
                    "dsporder": index + 1
                });
                p = _.mapKeys(p, (value, key) => {
                    // let keyList = key.split("");
                    // let isHasNum = keyList.some((item) => {
                    //     return parseInt(item)
                    // });
                    // if (isHasNum == true) {
                    //     keyList.pop()
                    // };
                    // return keyList.join("");
                    if (key.indexOf("标") > -1) {
                        var ind = key.indexOf("标");
                        key = key.substr(0, ind);
                    }
                    return key;
                });
                return p;
            });
        }
        this.saveProInfo({
            ...project,
            "tasks": JSON.stringify(postDataTask),
            categoryid: this.categoryid
        });
        this.form.resetForm();
        this.formB.resetForm();
        this.form = new WeaForm();
        this.formB = new WeaForm();
        this.uploadTaskRefs = null;
        this.uploadProjectRefs = null;
        this.uploadSize = [];
        this.submitFlag = false;
        this.uploadRefSize = 0;
        this.suffix = 1;

    }
    //搜索
    setSearchValue(v) {
        this.value = v;
        this.setUpdate();
    }

    //tab切换key
    changeTab(v) {

        this.tabkey = v;
        this.abcSelected = '';
        this.setUpdate();
    }
    /**
     * 触发方式（0卡片触发、1触发流程）（key 0新建、1汇报、2分解、3催办、4变更）
     * @param {*} params
     */
    @action
    getActionSetting(id, bool) {
        this.form.isFormInit = false;
        this.formB.isFormInit = false;
        if (bool == true) {
            this.cancelIdList.push(id);
            if (this.cancelIdList.length > 2) {
                this.cancelIdList.shift(); //确保数组只有2项
            }
            if (this.cancelIdList.length == 2) {
                if (this.cancelIdList[0] == this.cancelIdList[1]) {
                    null;
                } else {
                    this.form = new WeaForm();
                    this.formB = new WeaForm();
                    this.form.isFormInit = false;
                    this.formB.isFormInit = false;
                    this.condition = [];
                    this.listStoreB.condition = [];
                }
            }
        } //解决切换不同督办类型，可能弹出页面失败18.12.24
        let _this = this;
        Apis.getActionSetting({
            "categoryid": id,
            "actiontype": 0
        }).then(data => {
            if (parseInt(data.status) == 1) {
                if (data.isShowModel) {
                    _this.openModal(id, bool);
                } else {
                    if (data.status == "-1") {
                        message.error(data.error);
                    } else {
                        //window.open("/spa/workflow/index_form.jsp#/main/workflow/req?requestid="+data.newrequestid+"&workflowid="+data.flowid+"&categoryid="+id+"&actiontype="+0);
                        window.open("/spa/workflow/index_form.jsp#/main/workflow/req?iscreate=1&" + data.workflowid);
                    }
                }
            } else {
                message.error(data.error);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    //打开Dialog
    @action
    openModal(id, bool) {
        this.suffix = 1;
        if (bool == true) {
            this.beforeIdList.push(id);
            if (this.beforeIdList.length > 2) {
                this.beforeIdList.shift(); //确保数组只有2项
            }
            if (this.beforeIdList.length == 2 && this.beforeIdList[0] == this.beforeIdList[1]) {
                null;
            } else {
                this.clearForm();
            } //18.12.21解决非保存关闭，清空表单内容.
        }
        let typesCols = this.showDatas.typesCols;
        typesCols.forEach(element => {
            element.forEach(element => {
                if (element["wfbeans"]) {
                    element["wfbeans"].forEach(element => {
                        if (element["id"] == id) {
                            /*  if(element["triggertype"] == 1){
                                 window.open("/spa/workflow/index_form.jsp#/main/workflow/req?iscreate=1&workflowid="+element["flowid"]+"&categoryid="+element["id"]+"&triggertype=0");
                             }else{ */
                            this.categoryid = id;
                            if (element["visible"] == false) {
                                this.initForm();
                            }
                            element["visible"] = bool;
                            //}

                        }
                    });
                }
            });
        });
    }


    //刷新数据
    setUpdate() {
        const showDatas = {};

        //setTypesShow
        const {
            wftypes,
            tabkey,
            abcSelected,
            value = ''
        } = this;
        const _value = value.toUpperCase();

        let typesShow = [];
        wftypes && wftypes.map(w => {
            let wNew = objectAssign({}, w);
            if (_value !== "") {
                wNew.wfbeans = wNew.wfbeans.filter(b => {
                    return (b.name.toUpperCase().indexOf(_value) >= 0 || b.id.indexOf(_value) >= 0 || b.spell.indexOf(_value) >= 0)
                });
            }
            if (tabkey == '2') {
                wNew.wfbeans = wNew.wfbeans.filter(b => {
                    return b.wfColl == "1"
                });
            }
            typesShow.push(wNew); //typesShow <-- datas
        })
        typesShow = typesShow.filter(s => {
            const {
                wfbeans = []
            } = s;
            return wfbeans.length > 0;
        });
        showDatas.typesShow = typesShow;

        //setTypesCols
        const docWidth = document.documentElement.clientWidth;
        let typesCols = docWidth > 1400 ? [
            [],
            [],
            [],
            []
        ] : (docWidth > 1100 ? [
            [],
            [],
            []
        ] : (docWidth > 600 ? [
            [],
            []
        ] : [
                []
            ]));
        let colHeight = docWidth > 1400 ? [0, 0, 0, 0] : (docWidth > 1100 ? [0, 0, 0] : (docWidth > 600 ? [0, 0] : [0]));
        typesShow.length > 0 && typesShow.map(t => {
            const {
                wfbeans = []
            } = t;
            if (wfbeans.length >= 0) {
                let minH = Math.min.apply(Math, colHeight);
                for (let i = 0; i < colHeight.length; i++) {
                    if (colHeight[i] == minH) {
                        typesCols[i].push(t);
                        colHeight[i] += wfbeans.length + 3;
                        break;
                    }
                }
            }
        });
        showDatas.typesCols = typesCols;

        this.showDatas = {
            ...this.showDatas,
            ...showDatas
        };
    }

    //刷新dialog数据
    /*  refreshdate(){
         const dialogDatas = {};
         let componentDatas = [];

     } */

    /**
     * 校验真正的form
     */
    checkValidate = () => {
        let _this = this;
        return new Promise(function (resolve, reject) {
            _this.arrayValid = [];
            let filedsize = 0;
            let _index = 0;
            _this.listStoreB["condition"].map((c) => {//#587348 概述：E9，督办，立项，删除一个必填项为空的子任务后，点击保存，没反应
                filedsize = filedsize + c.items.length;
                c.items.map((item, index) => {
                    // console.log("item", _this.formB.getFormParams())
                    _this.formB.validate(item.domkey[0]).then(({ isValid }) => {//这是个异步的
                        _index = _index + 1;
                        _this.arrayValid.push(isValid);
                        if (_index == filedsize) {
                            resolve(_this.arrayValid);
                        }
                    })
                })
            })
        })

    }
}